package cn.itcast.bos.web.action.base;


import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.SystemOutLogger;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * Created by xbqco on 2018/7/13.
 */
@Controller
public class AreaController {
    @Autowired
    private AreaService areaService;

    @RequestMapping("/area_findpage")
    @ResponseBody
    public Map<String,Object> findPage(int page, int rows,Area model){
        Specification<Area> spec = new Specification<Area>() {
            @Override
            public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if(StringUtils.isNotBlank(model.getProvince())){
                    Predicate p1 = cb.like(root.get("province").as(String.class),"%"+model.getProvince()+"%");
                list.add(p1);
                }
                if(StringUtils.isNotBlank(model.getCity())){
                    Predicate p2 = cb.like(root.get("city").as(String.class),"%"+model.getCity()+"%");
                    list.add(p2);
                }
                if(StringUtils.isNotBlank(model.getDistrict())){
                    Predicate p3 = cb.like(root.get("district").as(String.class),"%"+model.getDistrict()+"%");
                    list.add(p3);
                }

                return cb.and(list.toArray(new Predicate[0]));
            }
        };




        Pageable pageable = new PageRequest(page-1,rows);
        Page p=areaService.findPage(spec,pageable);
        Map<String,Object> map = new HashMap<>();
        map.put("total",p.getTotalElements());
        map.put("rows",p.getContent());
        return map;


    }

    @RequestMapping("/area_save")
    public String save(Area model,String areaInfo){
        if(StringUtils.isEmpty(model.getId())){
        String id=UUID.randomUUID().toString();
        model.setId(id);}
        String[] pcd1 = areaInfo.split("/");
        String citycode= PinYin4jUtils.hanziToPinyin(pcd1[1].substring(0,pcd1[1].length()-1),"");
        String pcd2 = pcd1[0].substring(0,pcd1[0].length()-1)+pcd1[1].substring(0,pcd1[1].length()-1)
                +pcd1[2].substring(0,pcd1[2].length()-1);
        String pcdHead = array2String(PinYin4jUtils.getHeadByString(pcd2));
        model.setCity(pcd1[1]);
        model.setDistrict(pcd1[2]);
        model.setProvince(pcd1[0]);
        model.setCitycode(citycode);
        model.setShortcode(pcdHead);
        areaService.save(model);
        return "redirect:./pages/base/area.html";
    }

    public static String array2String(String[] ss){
        StringBuilder sb = new StringBuilder();
        for(String s:ss){
            sb.append(s);
        }
        return sb.toString();
    }


    @RequestMapping("/area_import")
    @ResponseBody
    public String batchImport(MultipartFile file){
        List<Area> list = new ArrayList<>();
        Workbook workbook = null;
        try {
            if(file.getOriginalFilename().endsWith("xls")){
                workbook  = new HSSFWorkbook(file.getInputStream());
            }
            if(file.getOriginalFilename().endsWith("xlsx")){
                workbook= new XSSFWorkbook(file.getInputStream());
            }

            Sheet sheet = workbook.getSheetAt(0);
            System.out.println("sheet的条目数"+sheet.getLastRowNum());
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    System.out.println(000);
                    continue;
                }
                if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
                    System.out.println(111);
                    continue;
                }

                Area area = new Area();

                String id = row.getCell(0).getStringCellValue();
                area.setId(id);
                String province = row.getCell(1).getStringCellValue();
                area.setProvince(province);
                String city = row.getCell(2).getStringCellValue();
                area.setCity(city);
                String district = row.getCell(3).getStringCellValue();
                area.setDistrict(district);
                String citycode = PinYin4jUtils.hanziToPinyin(city, "");
                area.setCitycode(citycode);
                String cut = province.substring(0, province.length() - 1) + city.substring(0, city.length() - 1)
                        + district.substring(0, district.length() - 1);

                String[] headCode = PinYin4jUtils.getHeadByString(cut);
                StringBuilder sb = new StringBuilder();
                for (String s : headCode) {
                    sb.append(s);
                }
                area.setShortcode(sb.toString());
                String postcode = row.getCell(4).getStringCellValue();
                area.setPostcode(postcode);
                list.add(area);
            }
            areaService.save(list);
            System.out.println("保存的数目"+list.size());
            return "0";
                }catch(Exception e){

            return "1";
        }


    }
    }